<?php
include('inc/dbFun.php');
class MysqlDao {
  
	///初始化 
	public function con(){
		DB_Connection(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD,DB_DATABASE);
	}
	
	//静态数据连接
	public static function conn()
	{
		DB_Connection(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD,DB_DATABASE);
	}	
	
	//查看总数
	protected function viewTableCount($table ,$row)
	{
		$where = empty($row) ? "" : ' where '.$row;
		$sql = "select count(*) from $table $where";
	  	return DB_Result($sql);
	}
	
	//工作报告分页
	protected function wordSummaryCoun($departmentId)
	{
		$sql  = "select count(w.id) from wordsummary as w  left join userInfo as u on w.userId = u.id ";
		$sql .= "where u.departmentId =".$departmentId;
		return DB_Result($sql);
	}
	
	//查看用户列表
	protected function viewUserList()
	{		
		$where = '';
		$list = array();

		if ($_SESSION['type'] == 0) {
			exit; 
		} elseif ($_SESSION['type'] == 1) {
			$where = ' where u.departmentId = '.$_SESSION['departmentId'];
		}

		$sql = 'select u.id, u.name, u.departmentId, u.isOut, u.purview, u.lastLoginTime, u.qq';
		$sql .= ', u.type, u.level, u.lastLoginTime, u.count, u.entryDate, u.leaveDate, u.kpiType from userInfo as u '.$where.' order by u.id desc';

		$rs = DB_Query($sql);
		while ($row = DB_Set($rs)){
	       $list[] = array(
	          "id" => $row['id'],
	          "name" => $row['name'],
	          "type" => $row['type'] ,
			  "level" => $row['level'],
	          "isOut" => $row['isOut'] ,
	          "departmentId" => $row['departmentId'] ,
	          "lastLoginTime" => $row['lastLoginTime'] ,
	          "purview" => $row['purview'] ,
	          "lastLoginTime" => date("Y-m-d H:i:s" , $row['lastLoginTime']),
	          "count" => $row['count'],
	          "qq" => $row['qq'],
	          "entryDate" => $row['entryDate'],
	          "leaveDate" => $row['leaveDate'],
	          "kpiType" => $row['kpiType']
	       );
		}	
		
		return $list;
	}
	
	//查看部门列表
	public function viewDepartmentList()
	{
		return DB_ResultSet('select  * from department');
	}
	
    //查看产品项目列表
    protected function viewResourceList()
    {
    	if ($_SESSION['type'] == 2 || $_SESSION['departmentId'] == 1) {
    		return DB_ResultSet("select id , name from resource");
      }
    }
    
    //查看项目列表
    protected function viewPorjectList($start , $userId)
    {
        if ($_SESSION['type'] == 2 || $_SESSION['departmentId'] == 1) {
		$list = '';
        if ($_SESSION['type'] == 2){ 
            $where = empty($userId) ? "" : 'where userId = '.$userId;
        	$sql  = "select   p.id ,p.title , p.state , p.unit , p.num ,  from_unixtime(recordTime) ";
        	$sql .= "as recordTime,u.name , l.name as stateName , u.id as userId , r.name as resource ";
        	$sql .= "from project as  p left join userInfo as u on p.userId = u.id left join resource as r ";
        	$sql .= "on p.resourceId = r.id left join userInfo as l on p.stateUserId = l.id $where order ";
        	$sql .= "by p.id desc  limit $start ,".PAGESIZE;
        }else{
           $sql = "select p.id , p.title , p.state , p.unit , p.num , FROM_UNIXTIME(recordTime) as recordTime, u.name , l.name as stateName , u.id as userId , r.name as resource from privilege as pp left join  project as p on pp.projectId = p.id left join userInfo as u on p.userId = u.id left join resource as r on p.resourceId = r.id left join userInfo as l on p.stateUserId = l.id where pp.userId = $_SESSION[id] order by p.id desc limit $start ,".PAGESIZE;
        }
        $rs = DB_Query($sql);
           	while ($row = DB_Set($rs)) {
	    		$list[] = array(
	    		  "id" => $row['id'],
	    		  "userId" => $row['userId'],
	    		  "title" => $row['title'],
	    		  "state" => $row['state'],
	    		  "unit" => $row['unit'],
	    		  "stateName" => $row['stateName'],
	    		  "name" => $row['name'],
	    		  "resource" => $row['resource'],
	    		  "num" => $row['num'],
	    		  "recordTime" => date('Y-m-d' ,strtotime($row['recordTime']))
	    		);
	    	}
	    	return $list;
        }
    }
    
    //状态切换
    public function stateSwitch(){
     if ($_SESSION['type'] == 2 || $_SESSION['departmentId'] == 1) {
     	$parameter = stageRouter();
    	if (count($parameter == 3)) {
    		$id = intval($parameter[1]);
    		$state = intval($parameter[2]);
    		if($_SESSION['type'] < 2) $this->IsView($id);
    	    DB_Query('update project set state ='.$state.' , stateUserId = '.$_SESSION['id'].' where id='.$id);
    	   Header("Location:?q=projectList");
    	}
     }
    }    
    
    //查看详细页面
    protected function viewDetailsData($id ,$table){
    	$sql = "select * from $table where id=".$id;
       	return DB_QuerySet($sql);
    }
    
    //查看详细楼层
    protected function viewDetailsBss($id ,$start)
    {
    	if ($_SESSION['type'] == 2 || $_SESSION['departmentId'] == 1) {
	    	$sql  = "select d.content , FROM_UNIXTIME(d.recordTime) as recordTime , u.name as userName ";
	    	$sql .= "from followinfo as d left join userInfo as u on d.userId = u.id  where child =".$id;
	    	$sql .= " order by d.id desc limit $start ,".PAGESIZE;
	    	return DB_ResultSet($sql);
      }
    }
    
    //查看是否有权限
    protected function IsView($id)
    {
     if ($_SESSION['type'] != 2) {    
    	$sql = "select * from privilege where userId= $_SESSION[id] and projectId = $id";
        $result = DB_Rows($sql);
        if(empty($result)) {
        	Header("Location:?q=projectList");
        }
      }
    }
    
    //查看业务
    protected function getUserList($id)
    {
    	$sql  = "select u.name ,u.id  , u.departmentId , (select id from privilege where userId =";
    	$sql .= "u.id and projectId = $id) as value from userInfo as u where u.isOut =0  and u.type ";
    	$sql .= " < 2 and u.departmentId =1";
    	return DB_ResultSet($sql);    	
    }
    
    //设置权限信息
    public function setUserAssgin()
    {
		if ($_SESSION['type'] != 2) exit; 
    	$parameter = stageRouter();
    	$isRs = DB_Query("select * from privilege where projectId = $parameter[1] and userId=".$parameter[2]);
    	if (DB_getRow($isRs) == 0) {
    	   $sql  = "insert into privilege (userId , projectId) values ($parameter[2] , $parameter[1])";	
    	   $result = 1;
    	 }else {
    	   $sql =  "delete from privilege where projectId = $parameter[1] and userId=".$parameter[2];
    	   $result = 0;
    	 }
    	DB_Query($sql);
    	echo  $result;  	 
    }
    
    //查看当天报告
    protected function viewGetDaySummary()
    {
    	$sql = "select summary , plan from wordsummary where userId = $_SESSION[id] and ";
    	$sql .= " recordTime ='".date("Y-m-d")."'";
    	return DB_QuerySet($sql); 	
    }
    
    //查看工作报告分页
    protected function summaryListData($start , $when ,$end)
    {
	  $list = array();
	  $where = "";
      if($_SESSION['type'] < 2){
    	if ( $_SESSION['purview'] == 1 || $_SESSION['type'] > 0) {
    		if (empty($when)) {
    			$where = 'where u.departmentId ='.$_SESSION['departmentId'];
    		}else {
    			$where = 'where u.departmentId ='.$_SESSION['departmentId'].' and '.$when;
    		}    	
    	}else{
    		$where = ' where userId ='.$_SESSION[id];
    	}
      }else {
        $where = empty($when) ? '' : 'where '.$when;  
      }
      $sql = "select w.id ,replace( w.summary ,' ' ,'&nbsp;&nbsp;') as  summary , w.recordTime ,";
      $sql .= " replace( w.plan ,' ' ,'&nbsp;&nbsp;') as plan , u.name , u.id as userId, d.name as ";
      $sql .= " department , u.departmentId from wordsummary as w left join userInfo as u on w.userId";
      $sql .= " = u.id  left join department as d on u.departmentId = d.id ".$where." order by w.id ";
      $sql .= " desc limit $start ,".$end;
      $rs = DB_Query($sql);
    	if (DB_getRow($rs) > 0) {
    		$shopping = array();
    		if (!empty($_SESSION['shopping'])) {
    			$shopping = unserialize($_SESSION['shopping']);
    		}
    		
    		while ($row = DB_Set($rs)) {
    			if(gettype($shopping) == 'array') $flag = in_array($row['id'],$shopping) ? 1 : 0;
    			$list[] = array(
    			  "id" => $row['id'],
    			  "name" => $row['name'],
    			  "userId" => $row['userId'],
    			  "department" => $row['department'],
    			  "departmentId" => $row['departmentId'],
    			  "shopping" => $flag,
    			  "recordTime" => $row['recordTime'],
    			  "plan" => nl2br($row['plan']),
    			  "summary" => nl2br($row['summary'])
    			);
    		}
    		
    	}
     	return $list;
    }
   
    //查出指定部门的用户
    public function viewDepartmentUserList($id){
        $where = 00 == $id ? '' : " and departmentId =".$id;
        $sql = 'select id, name , qq, type , departmentId from userInfo  where name != "'.FOUNDER.'" and isOut = 0'.$where;
        return DB_ResultSet($sql);
    }
    
    //导出工作报告
    static  function exportSummaryData($date){
    	if ($_SESSION['type'] == 0) exit;
     	if ($date == 1) {
     		$list = unserialize($_SESSION['shopping']);
     		if (gettype($list) == "array") {
     			$list = join("," , $list);
     			$sql = "select u.name , w.summary , w.plan ,w.recordTime from wordsummary as w ";
     			$sql .= "left join userInfo as u on w.userId = u.id where w.id in($list)";
     		}else {
     			exit(print($_SESSION['shopping']));
     		}
     	}else { 	
     	  if($_SESSION['type'] == 0) exit;
     	  if ($_SESSION['type'] == 2) {
     	  	$sql  = 'select u.name , w.summary , w.plan , w.recordTime  from wordsummary as w ';
     	  	$sql .= 'left join userInfo as u on w.userId = u.id where DATE_SUB(CURDATE(), ';
     	  	$sql .= ' INTERVAL 7 DAY) <= date(recordTime)'; 
     	  }else{
     	  	$sql = 'select u.name , w.summary , w.recordTime  from wordsummary as w left join ';
     	  	$sql .= 'userInfo as u on w.userId = u.id where DATE_SUB(CURDATE(), INTERVAL 7 DAY) ';
     	  	$sql .= ' <= date(recordTime) and u.departmentId='.$_SESSION['departmentId'];
     	  }
          
     	}
     	$rs = DB_Query($sql);
        while ($row = DB_Set($rs)) {
        	$listData[] = array($row['name'] , nl2br($row['summary']) ,nl2br($row['plan']), $row['recordTime']);    
        }         
          return $listData;
     }
     
    //查看导出的日期
    static function maxSummaryDate(){
    	if($_SESSION['type'] == 0) exit;
    	$sql = 'select w. recordTime , count(*) as max from wordsummary as w left join userInfo ';
    	$sql .= ' as u on w.userId = u.id  where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= ';
    	$sql .= 'date(w.recordTime) and u.departmentId = 1 group by w.recordTime order by max desc limit 1';
    	if ($_SESSION['type'] == 2) {
    		$sql =  'select recordTime  , count(*) as max from wordsummary where DATE_SUB(CURDATE()';
    		$sql .= ', INTERVAL 7 DAY) <= date(recordTime)  group by recordTime order by max desc limit 1';
     	}
    	return DB_Result($sql);
    }
     
    //导出楼层信息
    public static function exportProjectReply($id){
     if ($_SESSION['type'] != 2) exit;
     	$sql = "select u.name , FROM_UNIXTIME(d.recordTime) as recordTime ,d.content from ";
     	$sql .= "followinfo as d left join userInfo as u on d.userId = u.id  where ";
     	$sql .= " child =$id order by d.id desc";
     	return DB_ResultSet($sql);
    }
    
    //查看部门与资源的统计列表
    public function viewRDList($id){
    	if($_SESSION['type'] == 0) exit;
    	if (1 == $id) {
    		$sql = 'select d.id  , d.name ,  (select count(*) from userInfo where departmentId =d.id';
    		$sql .= ' ) as count  from department as d' ;    		
    	}else {
    		$sql = 'select r.id , r.name , (select count(*) from project where resourceId = r.id)';
    		$sql .= ' as count from resource as r';
    	}   
    	return DB_ResultSet($sql);
    }
    
    //查看报备信息分页 
    protected function viewReportedList($strart , $type , $action){
      if ($_SESSION['type'] == 2 || $_SESSION['departmentId'] == 1) {
      	$list = array();
      	$where = '';
    	if($type == 1){
    		$where =' where u.id ='.$action;
    	}
    	elseif ($type == 2) {
    		$where =' where r.'.$action[0].' like "%'.$action[1].'%"';
    	}
    	$sql  = 'select r.id , r.scale , r.recordTime , r.title , r.unit , u.name , rr.name as ';
    	$sql .= 'resourceName from reported as r left join userInfo as u on r.userId = u.id left ';
    	$sql .= 'join resource as rr on r.resourceId = rr.id '.$where.' order by r.id desc limit ';
    	$sql .=  $strart.' ,'.PAGESIZE; 
      	$rs = DB_Query($sql);
        while ($row = DB_Set($rs)) {
        	$Time = countdown($row['recordTime']);
         	$list[] = array(
			 'id' => $row['id'],        	  
			 'title' => $row['title'],        	  
			 'scale' => $row['scale'],        	  
			 'name' => $row['name'],        	  
			 'unit' => $row['unit'],        	  
			 'recordTime' => $row['recordTime'], 
			 'isOver' => $Time[0] > 30 ? 3 : 2,
			 'tip' => $Time[1].$Time[2].$Time[3].$Time[4],    	  
			 'resourceName' => $row['resourceName']      	  
        	);
        
        }              
        return $list;
      }
     }

    //查询相关主题
    public function viewRelatedTitle(){
    	if ($_SESSION['departmentId'] == 1 || $_SESSION['type'] == 2) { 
    	header("Content-type: text/xml");
    	$sql = 'select id , title from reported where title like "%'.urldecode($_GET['title']).'%"';
    	$rs = DB_Query($sql);
        echo "<?xml version=\"1.0\" encoding=\"utf-8\"?><list>";
        while ($row = DB_Set($rs)) {
        	 echo '<title id="'.$row['id'].'">'.$row['title'].'</title>';
        }    
        echo '</list>';
     }
    }
    
    //查询发送历史与报备的详细数据
    protected function viewRSDetailsData($id , $type){
    	if (0 == $type) {
    		$sql  = 'select  r.id , r.title , r.linkman , r.phone , r.mail  , r.anzeigeInc , ';
    		$sql .= ' r.anzeigeLinkman , r.anzeigePhone , r.anzeigeMail , r.scale , r.unit , ';
    		$sql .= ' r.reflect ,r.recordTime , u.name , rr.name as resoureName from reported ';
    		$sql .= ' as r left join userInfo as u on r.userId = u.id left join resource as rr ';
    		$sql .= 'on r.resourceId = rr.id where r.id = '.$id;
    	}else{
    		$sql = 'select s.title , s.content , s.recordTime , s.mail ,  u.name  from sendhistory';
    		$sql .= ' as s left join userInfo as u on s.userId = u.id where s.id ='.$id;
    	}
        return DB_QuerySet($sql);
    }
    
    
    //查询发送历史
    protected function viewSendHiStory($start){
    	if ($_SESSION['type'] == 0) exit; 
    	$list = array();
    	$sql = 'select m.id , m.title , m.recordTime , m.mail  , u.name from  sendhistory as m left join userInfo as u on m.userId = u.id  order by m.id desc  limit '.$start.' ,'.PAGESIZE;
        $rs = DB_Query($sql);
        while ($row = DB_Set($rs)) {
        	$count = explode(',' , $row['mail']);			
        	$list[] = array(
        	  'id' => $row['id'],
        	  'title' => $row['title'],
        	  'count' => count($count),
        	  'recordTime' => $row['recordTime'],
        	  'name' => $row['name']
        	);
        }
        return $list;
    }
    
    
    /*
     * 插入部分
     */
    
    //插入用户基本信息
    public function addUserInfo()
    {
		echo 'start..';
    	if ($_SESSION['type'] == 0) 
			exit; 

    	$sql = "insert into userInfo (name , pass , departmentId , qq) values ";
    	$sql .= "('".trim($_POST['name'])."' ,'".sha1($_POST['pass'])."' ,";
    	$sql .= intval($_POST['departmentId'])." , '".trim($_POST['qq'])."')";
    	$result = DB_Query($sql);
    	if (empty($result)) {
    		exit(message('添加失败'));
    	}

    	Header("Location:?q=userList");
    }
    
    //插入新部门 \ 新资源项目
    public function addDepartment()
    {
    	if ($_SESSION['type'] != 2) exit; 
    	$table = $_GET['type'] == 0 ? "department" : "resource";
    	$sql = "insert into $table (name) values ('".urldecode($_GET['name'])."')";
    	DB_Query($sql);
    	echo DB_InserId();
    }
    
    //插入项目信息
    public function addProjectInfoSava()
    {
    	if ($_SESSION['type'] == 2 || $_SESSION['departmentId'] == 1) { 
    	if (!empty($_POST['id'])) {
    	  $sql = "update project set title = '$_POST[title]' , linkman = '$_POST[linkman]'";
    	  $sql .=" , unit = '$_POST[unit]' , phone = '$_POST[phone]' , address = '$_POST[address]'";
    	  $sql .= " , mail = '$_POST[mail]' , num = '$_POST[num]' , anzeigeInc = '$_POST[anzeigeInc]'";
    	  $sql .= " , anzeigeLinkman = '$_POST[anzeigeLinkman]' , anzeigePhone = '$_POST[anzeigePhone]'";
    	  $sql .= " , anzeigeMail = '$_POST[anzeigeMail]' , remark = \"".$_POST['remark']."\" ,";
    	  $sql .= " resourceId = '$_POST[resourceId]' where id =".intval($_POST['id']);
    	  DB_Query($sql);
    	}else {
    	  $sql = "insert into project (title , linkman , unit , phone , address , mail , num , anzeigeInc , ";
    	  $sql .= "anzeigeLinkman , anzeigePhone , anzeigeMail , recordTime ,remark ,resourceId , userId ,";
    	  $sql .= " stateUserId) values ('$_POST[title]','$_POST[linkman]' ,'$_POST[unit]' , '$_POST[phone]'," ;
    	  $sql .= "'$_POST[address]', '$_POST[mail]',".intval($_POST['num']).",'$_POST[anzeigeInc]',";
    	  $sql .= "'$_POST[anzeigeLinkman]','$_POST[anzeigePhone]','$_POST[anzeigeMail]',UNIX_TIMESTAMP(),\"";
    	  $sql .= addslashes($_POST['remark'])."\" , ".intval($_POST['resourceId'])." , $_SESSION[id] , $_SESSION[id])";
          DB_Query($sql);
    	  DB_Query("insert into privilege (userId , projectId) values ($_SESSION[id] , ".DB_InserId().")"); 
    	}    	
        Header("Location:?q=projectList");
     }
    }
    
    //插入工作报告
    protected function addWordSummary()
    {
    	$sql = "select id from wordsummary where recordTime = '".date("Y-m-d")."' and userId = ".$_SESSION['id'];
    	$rs = DB_Query($sql);
    	if (DB_getRow($rs) == 0) {
          $sql = "insert into wordsummary (`userId`,`summary`,`plan` ,`recordTime` ) values (";
          $sql .= intval($_SESSION['id']).",\"".addslashes($_POST['content'])."\" ,\"";
          $sql .= addslashes($_POST['plan'])."\" , now() )";    		
    	}else {
    	  $sql = "update wordsummary set summary =  \"".addslashes($_POST['content'])."\" , ";
    	  $sql .=" plan = \"".addslashes($_POST['plan'])."\" where id =".DB_getResult($rs);
    	}
    	DB_Query($sql);    	
    }    

    //插入项目报备
    public function addreportedSava()
    {
    	if ($_SESSION['type'] == 2 || $_SESSION['departmentId'] == 1) {
    	  if(!empty($_POST['id'])){
    	  	 $sql = 'update reported set title = "'.$_POST['title'].'" , resourceId = ';
    	  	 $sql .= intval($_POST['resourceId']).' , linkman = "'.$_POST['linkman'];
    	  	 $sql .= '" , phone="'.$_POST['phone'].'" ,mail = "'.$_POST['mail'].'" ,scale = ';
    	  	 $sql .= intval($_POST['scale']).',anzeigeInc ="'.$_POST['anzeigeInc'].'" , anzeigeLinkman="';
    	  	 $sql .= $_POST['anzeigeLinkman'].'" ,anzeigePhone ="'.$_POST['anzeigePhone'].'" ,';
    	  	 $sql .= 'anzeigeMail="'.$_POST['anzeigeMail'].'" , unit = "'.$_POST['unit'].'" ';
    	  	 $sql .= ',reflect = "'.addslashes($_POST['reflect']).'" where id ='.intval($_POST['id']);
             if(0 == DB_Query($sql)){
             	exit(message("更新数据出错".DB_getError()));
             }
    	  }else {
    	  	$sql = 'insert into reported (title , resourceId, linkman ,phone ,mail , scale , ';
    	  	$sql .= 'anzeigeInc , anzeigeLinkman , anzeigePhone , anzeigeMail , unit , recordTime';
    	  	$sql .= ' , reflect , userId) values ("'.addslashes($_POST['title']).'" , ';
    	  	$sql .= intval($_POST['resourceId']).' ,"'.$_POST['linkman'].'" ,"'.$_POST['phone'];
    	  	$sql .= '" ,"'.$_POST['mail'].'" , '.intval($_POST['scale']).' ,"'.$_POST['anzeigeInc'];
    	  	$sql .= '" , "'.$_POST['anzeigeLinkman'].'" , "'.$_POST['anzeigePhone'].'" , "';
    	  	$sql .= $_POST['anzeigeMail'].'" , "'.$_POST['unit'].'" , UNIX_TIMESTAMP() , "';
    	  	$sql .= addslashes($_POST['reflect']).'" , '.$_SESSION['id'].' )';    	  	 
            if(0 == DB_Query($sql)){
            	exit(message("插入数据出错".DB_getError() , "?q=addReportedInfo"));
            }
    	  }    			
    	Header("Location:?q=reportedList");    
    	}	
    }
    
    //插入工作跟进信息
    protected function addFollowinfo()
    {
      if ($_SESSION['type'] == 2 || $_SESSION['departmentId'] == 1) {
    	$sql = "insert into followinfo (child , content , userId , recordTime) values ";
    	$sql .= "(".intval($_POST['id'])." , \"".$_POST['content'] ."\" , ";
    	$sql .= intval($_SESSION[id])." , UNIX_TIMESTAMP()) ";
    	DB_Query($sql);
      }
    }
    
    //插入发送历史
    protected function addMailData($title , $content, $mail){
       if ($_SESSION['type'] == 0) exit;
       $sql = 'insert into sendhistory(`title` , `content` , `mail` ,`userId` , `recordTime` ) values("';
       $sql .= $title.'" , "'.addslashes($content).'" , "'.$mail.'" ,'.$_SESSION['id'].' , now())';
       DB_Query($sql);
    }
   
    //用户登录验证
   public function volidLogin()
    {
		$backBtn = '&nbsp;<a href="index.php">返回</a>';
    	$count = empty($_COOKIE['count']) ? 0 : intval($_COOKIE['count']);
    	setcookie('count' ,$count + 1 );

    	if ( $count >= 1) {
    		if(intval($_POST['code']) != $_SESSION["code"]) {
				exit(message('验证码错误','index.php'));
    		}
    	}elseif ($count >5 ){
			message('请不要尝试非法登录！你的帐号已经暂时被冻结！','index.php');
    		exit;
    	}

        $sql = "select id , name , type , departmentId, purview from userInfo where isOut = 0 ";
        $sql .= "and name = '$_POST[userName]' and pass = '".sha1($_POST['pass'])."'";
    	$rs = DB_Query($sql);
    	if (DB_getRow($rs) > 0) {
    	  $time = mktime();
    	  $row = DB_Set($rs);
    	  $_SESSION['id'] = $row['id'];
    	  $_SESSION['name'] = $row['name'];
    	  $_SESSION['type'] = $row['type'];
    	  $_SESSION['departmentId'] = $row['departmentId'];
    	  $_SESSION['purview'] = $row['purview'];

    	   DB_Query("update userInfo set count = count + 1 , lastLoginTime = $time where id =".$_SESSION['id']);
    	}else {
    		exit(message('密码错或者用户名不存在','index.php'));
    	}

    	unset($_SESSION['code']);
    	setcookie("count","",time()-60);
    	setcookie('userName' , $_SESSION['name'] , time()+3600*24*30);
    	Header("Location:?q=main");
    	exit;
    }
    
   //根据权限修改用户资料
   public function editUserInfo()
   {
		if ($_SESSION['type'] == 0) 
			exit;
		
		$sql = '';
		$pwd = $_POST['pass'];
		$kpiType = $_POST['kpiType'];
		$entryDate = $_POST['entryDate'];
		$leaveDate = $_POST['leaveDate'];
	  
		if ($_SESSION['type'] == 2) {
			$sql = "update userInfo set";
			if( !empty( $entryDate ) && $entryDate != "" ) {
				$sql .= " entryDate=\"".$entryDate."\", ";
			} else {
				$sql .= " entryDate=NULL, ";
			}
			if( !empty( $leaveDate ) && $leaveDate != "" ) {
				$sql .= " leaveDate=\"".$leaveDate."\", ";
			} else {
				$sql .= " leaveDate=NULL, ";
			}
			$sql .= " kpiType=".intval($kpiType).", ";
			if( !empty( $pwd ) && $pwd != "" ) {
				$sql .= " pass = '".sha1($pwd)."', ";
			} 
			$sql .= " qq = '".$_POST['qq']."', level = ".intval($_POST['level']).", type = ".intval($_POST['power'])." , departmentId = ".intval($_POST['departmentId'])." where id = ".$_POST['id'];
		} else {
			if( empty( $pwd ) || $pwd == "" ) {
				$sql = "update userInfo set qq = '".$_POST['qq']."' where id = ".$_POST['id'];
			} else {
				$sql = "update userInfo set qq = '".$_POST['qq']."', pass = '".sha1($pwd)."' where id = ".$_POST['id'];
			}
		}
		DB_Query($sql);
		
		Header("Location:?q=userList");	   	
   }
   
   //修改工作报告权限
   public function viewUserSummary(){
   	 if ($_SESSION['type'] == 0) exit;
   	 DB_Query("update userInfo set purview = IF(purview=1,0,1)  where id  = ".intval($_GET[id]));
   	 Header("Location:?q=userList");	 
  }
    
   //修改项目资源与部门信息
   public function editOtterInfo()
   {
        if ($_SESSION['type'] != 2) exit; 
        $isType = intval($_GET['id']);
   	    $table = $isType == 1 ? "department" : "resource";
   	    if (0 == $_GET['type']) {
   	    	$sql = "update $table set name = '$_POST[name]' where id =".intval($_POST['id']);
   	    }else {
   	    	$sql = "insert into $table (name) values ('$_POST[name]')";
   	    }
  	    DB_Query($sql);
   	    Header("Location:?q=resourceDepartmentList/$isType");
   }
   
   //验证密码
   public function ChangePassValid()
   {
   	 if (!empty($_POST['value'])) {
     	 $pass = sha1(urldecode($_POST['value']));
	     echo DB_Rows("select id from userInfo where name='$_SESSION[name]' and pass = '$pass'"); 	 	
   	 }elseif (!empty($_POST['pass'])) {
   	 	 $pass = sha1(urldecode($_POST['pass']));
   	 	 $sql = "update userInfo set pass = '$pass' where id =".$_SESSION['id'];
         echo DB_Query($sql) ;
   	 }

   }
   
   
   
   /*
    * 删除部分
    */
  
   //员工离职
   public function Separation(){
   	 $id = intval($this->parameter[1]);
   	 if(!empty($id)){
   	 	DB_Query('update userInfo set isOut = 1 where id='.$id);
   	 }
   	 Header("Location:?q=userList");
   }
   
   //删除整个项目
   public function removeProjectData(){
      if ($_SESSION['type'] != 2) exit;      
      $id = stageRouter();
      $id = intval($id[1]);
      DB_Query("delete from project where id=$id");
      DB_Query("delete from privilege where projectId = $id");
      DB_Query("delete from followinfo where child = $id");
      Header("Location:?q=projectList");
   }
   
   //删除用户
   public function removeUserInfpSava()
   {
   	 if ($_SESSION['type'] != 2) exit; 
	 $sql  ="delete from userInfo where `id` = ".intval($_GET['id']);
   	 DB_Query($sql);
	 Header("Location:?q=userList");
   }
  
   //删除资源与部门信息
   public function removeDepartmentSava()
   {
   	if ($_SESSION['type'] != 2) exit; 
   	 $type = intval($_GET['type']); 
     $table = $type == 1 ? 'department' : 'resource';
   	 DB_Query("delete from $table where id =".intval($_GET['id']));
   	 Header("Location:?q=resourceDepartmentList/$type");
   }
    
   
   /*
	* 叫餐部分
	* 新增 商家、菜名
	*/
   public function addMeal(){
   	  $parentId = intval($_POST['parentId']);
   	  $name = $_POST['name'];
   	  $price = $_POST['price'];
   	  if (!empty($name)) {   	  	 
   	  	$sql = 'insert into mealType(name ,parentId , price) values("%s" , %d ,"%s")';
   	  	echo $sql = sprintf($sql , $name , $parentId , $price);
   	  	DB_Query($sql);
   	  	Header("Location:?q=mealType");
   	  }else{
   	  	message('参数错误 操作失败');
   	  }
   }
   
   //修改商家、菜名
   public function editMeal(){
   	 $name = $_POST['name'];
   	 $id = intval($_POST['id']);
     $price = $_POST['price'];
     if($id > 0 && !empty($name)){
     	$temp =  empty($price) ? '' : ', price = "'.$price.'"';
      	$format = 'update mealType set name = "%s" '.$temp.' where id = %d';
      	$sql = sprintf($format , $name , $id);
      	DB_Query($sql);
      	Header("Location:?q=mealType");
     }else {
     	message('参数错误 操作失败');
     }
   }
   
   //删除
   public function removeMeal(){
   	 $id = intval($_GET['id']);
   	 if($_SESSION['type'] > 0){
   	 	$sql = 'delete from mealType where id = '.$id.' or parentId = '.$id ;
        DB_Query($sql);
      	Header("Location:?q=mealType"); 	 	
   	 }else{
   	 	message('权限不够 操作失败');
   	 }
   }
   
   //添加叫餐
   public function addMenu(){
   	 $dayKey = date('Ymd');
   	 $mealId = intval($_GET['mealId']);
   	 $uId = intval($_GET['uid']);
   	 if (0 < $mealId && 0 < $uId) {
   	 	$sql = 'insert into menu values(null, %d , %d , %d ,UNIX_TIMESTAMP() , %d)';
   	 	$sql = sprintf($sql ,$mealId,$uId  ,$dayKey ,$_SESSION['id'] );
   	 	DB_Query($sql);
   	 	Header("Location:?q=todayMenu"); 
   	 }
		message('参数错误 操作失败');
   }
   
   public function editMenu(){
   	 $id = intval($_GET['id']);
   	 $mealId = intval($_GET['mealId']);
   	 $uId = intval($_GET['uid']);
   	 if (0 < $mealId && 0 < $id && 0 < $uId) {
   	 	$format = 'update menu set mealId = %d , uId = %d ,userId =%d , unixTime = UNIX_TIMESTAMP() where id = %d';
   	 	$sql = sprintf($format , $mealId , $_SESSION['id'] ,$uId ,$id);
   	 	DB_Query($sql);
   	 	Header("Location:?q=todayMenu"); 
   	 }
		message('参数错误 操作失败');
   }
   
   protected function mealTypeList($type){
   	 if (0 == $type) {
   	 	$sql = 'select id , name , price ,parentId from mealType where parentId = 0';
   	 }else{
   	 	$sql = 'select id , name , price ,parentId from mealType where parentId != 0';
   	 }
   	 return DB_ResultSet($sql);
   }
   
   protected function currentMenu(){
   	 $dayKey = date('Ymd');
   	 $sql = 'select m.id , m.userId ,m.mealId ,u.name as userName , t.name , t.parentId ,t.price ,FROM_UNIXTIME(m.unixTime)';
   	 $sql .= ' as time  from menu as m inner join userInfo as';
   	 $sql .= ' u on m.uId = u.id  inner join mealType as t on m.mealId = t.id where m.dayKey ='.$dayKey;
   	 return DB_ResultSet($sql);
   }
   
   protected function distinctMealType(){
   	$dayKey = date('Ymd');
   	$sql = 'select distinct(select name from mealType where id = t.parentId) as name , (select distinct id from mealType ';
   	$sql .= ' where id =t.parentId) as id  from menu as m left join mealType as t on  t.id =  m.mealId ';
   	$sql .= ' where m.dayKey ='.$dayKey;
   	$result = DB_Query($sql);
   	$names = array();
   	$keys = array();
   	while ($row = DB_Set($result)){
   		array_push($names , $row[0]);
   		array_push($keys , $row[1]);
   	}
   	$names = join($names , ',');
   	$keys = join($keys , ',');
   	return array($names , $keys);
   }
   
}

?>